<script setup lang="ts">
import type { Ref } from 'vue';
import dayjs from 'dayjs';
import { Search, Refresh } from '@element-plus/icons-vue';

import SubViewContainer from '@core/components/subLayout/SubViewContainer.vue';
import * as Enums from '@firewall/engine/Enums';
import TableWithPagination from '@core/components/TableWithPagination.vue';
import LogService, { OperationLog, LogSetting } from '@firewall/engine/LogService';
import FirewallInstanceSelector from '@firewall/components/FirewallInstanceSelector.vue';
import { FirewallSummary } from '@firewall/engine/Firewall';

const { t } = useI18n({ inheritLocale: true, useScope: 'local' });

const isTableLoading = ref(false);
const SeverityLevel = {
  All: Enums.FILTER_ALL,
  High: 'high',
  Normal: 'normal',
  Low: 'low',
};
const OperationBehavior = {
  All: Enums.FILTER_ALL,
  FirewallOpen: 'firewallOpen',
  FirewallStop: 'firewallStop',
  AddOrEditAccessControlRules: 'addOrEditAccessControlRules',
  EditAccessControlRules: 'editAccessControlRules',
  DeleteAccessControlRules: 'deleteAccessControlRules',
  ChangeIntrusionPreventionSettings: 'changeIntrusionPreventionSettings',
  AddAddressBook: 'addAddressBook',
  EditAddressBook: 'editAddressBook',
  DeleteAddressBook: 'deleteAddressBook',
  UserLogin: 'userLogin',
  UserLogout: 'userLogout',
};

const pagination = reactive({
  pageSize: 10,
  currentPage: 1,
});

const filters = reactive({
  severityLevel: SeverityLevel.All,
  operationBehavior: OperationBehavior.All,
  searchKeyword: '',
  timeRange: [
    dayjs().add(-1, 'days').format(Enums.REMOTE_DATE_FORMATTER),
    dayjs().format(Enums.REMOTE_DATE_FORMATTER),
  ],
});
const logSetting = reactive({} as Partial<LogSetting>);
const firewallInstance = reactive({} as Partial<FirewallSummary>);
const operationLogList: Ref<Array<OperationLog>> = ref([]);
const refreshTable = async () => {
  if (!firewallInstance.firewallId) {
    return;
  }
  isTableLoading.value = true;
  try {
    const response = await LogService.fetchOperationLogs({
      firewallId: firewallInstance.firewallId,
      severities: filters.severityLevel === SeverityLevel.All ? undefined : t(`severityLevel.${filters.severityLevel}`),
      action: filters.operationBehavior === OperationBehavior.All ? undefined : t(`operationBehavior.${filters.operationBehavior}`),
      content: filters.searchKeyword === '' ? undefined : filters.searchKeyword,
      beginTime: dayjs(filters.timeRange[0]).unix(),
      endTime: dayjs(filters.timeRange[1]).unix(),
      page: pagination.currentPage,
      size: pagination.pageSize,
    });
    operationLogList.value = response.list || [];
  } finally {
    isTableLoading.value = false;
  }
};
const refreshLogSetting = async () => {
  if (!firewallInstance.firewallId) {
    return;
  }
  isTableLoading.value = true;
  try {
    const remoteSetting = await LogService.fetchSetting({ firewallId: firewallInstance.firewallId });
    Object.assign(logSetting, remoteSetting);
  } finally {
    isTableLoading.value = false;
  }
};

const onFirewallChange = async (value: FirewallSummary) => {
  Object.assign(firewallInstance, value);
  await refreshLogSetting();
  await refreshTable();
};

const onTableRefresh = async () => {
  await refreshTable();
};

const getSeverityTagStyle = (severity: string) => {
  switch (severity) {
    case SeverityLevel.High: return 'high-severity';
    case SeverityLevel.Normal: return 'normal-severity';
    case SeverityLevel.Low: return 'low-severity';
    default: return 'normal-severity';
  }
};
</script>

<template>
  <SubViewContainer>
    <ElCard v-loading="isTableLoading">
      <FirewallInstanceSelector
          v-model:firewall="firewallInstance"
          class="firewall-instance-selector"
          @update:firewall="onFirewallChange"
        />
      <div class="table-controller">
        <div class="filters">
          <ElDatePicker
            v-model="filters.timeRange"
            type="datetimerange"
            class="date-range-picker"
            :format="t('dateFormatter')"
            :value-format="Enums.REMOTE_DATE_FORMATTER"
          />
          <ElSelect v-model="filters.severityLevel"  style="width: 130px;">
            <ElOption
               v-for="level in SeverityLevel"
              :key="level"
              :label="t(`severityLevel.${level}`)"
              :value="level"
            />
          </ElSelect>
          <ElSelect v-model="filters.operationBehavior" style="width: 200px;">
            <ElOption
              v-for="behavior in OperationBehavior"
              :key="behavior"
              :label="t(`operationBehavior.${behavior}`)"
              :value="behavior"
            />
          </ElSelect>
          <ElInput
            v-model="filters.searchKeyword"
            class="search-input"
            :placeholder="t('inputToSearchPlease')"
            @keyup.enter="onTableRefresh"
          >
            <template #append>
              <ElButton :icon="Search" @click="onTableRefresh" />
            </template>
          </ElInput>
          <ElButton :icon="Refresh" @click="onTableRefresh" />
        </div>
      </div>
      <TableWithPagination
        v-model:paginationPageSize="pagination.pageSize"
        v-model:paginationCurrentPage="pagination.currentPage"
        size="small"
        :data="operationLogList"
        paginationLayout="sizes, total, prev, pager, next"
        :paginationTotal="operationLogList.length"
      >
      <ElTableColumn :label="t('occurrenceTime')" >
          <template #default="scope">{{dayjs.unix(scope.row.updateTime).format(t('dateFormat'))}}</template>
        </ElTableColumn>
        <ElTableColumn :label="t('operationUser')" width="300px">
          <template #default="scope">{{ scope.row.uid }}</template>
        </ElTableColumn>
        <ElTableColumn :label="t('warningLevel')" >
          <template #default="scope">
            <div class="severity">
              <ElTag :class="getSeverityTagStyle(scope.row.severity)" >
                {{scope.row.severity}}
              </ElTag>
            </div>
          </template>
        </ElTableColumn>
        <ElTableColumn :label="t('operationalBehavior')" >
          <template #default="scope">{{ scope.row.action }}</template>
        </ElTableColumn>
        <ElTableColumn :label="t('logContent')" width="500px">
          <template #default="scope">
            {{scope.row.content}}
          </template>
        </ElTableColumn>
      </TableWithPagination>
    </ElCard>
  </SubViewContainer>
</template>

<i18n lang="yaml" locale="zh-CN">
  dateFormatter: 'YYYY-MM-DD HH:mm:ss'
  dateFormatterSend: 'YYYY-MM-DDHH:mm:ss'
  dateFormat: 'YYYY-MM-DD'
  warningLevel: '危险等级'
  operationalBehavior: '操作行为'
  severityLevel:
    all: '全部'
    high: '高危'
    normal: '中危'
    low: '低危'
  operationBehavior:
    all: '全部操作行为'
    firewallOpen: '开启防火墙'
    firewallStop: '关闭防火墙'
    addOrEditAccessControlRules: '增加访问控制规则'
    editAccessControlRules: '编辑访问控制规则'
    deleteAccessControlRules: '删除访问控制规则'
    changeIntrusionPreventionSettings: '变更入侵防御防护设置'
    addAddressBook: '增加地址簿'
    editAddressBook: '编辑地址簿'
    deleteAddressBook: '删除地址簿'
    userLogin: '用户登录'
    userLogout: '用户登出'
  inputToSearchPlease: '输入日志内容搜索'
  occurrenceTime: '发生时间'
  operationUser: '操作账号'
  logContent: '日志内容'
</i18n>

<style lang="scss" scoped>
.guide-steps {
  margin-bottom: 16px;
}

.table-controller,
.filters,
.quota-state {
  display: flex;
  flex-direction: row;
}

.table-controller {
  justify-content: flex-end;
  font-size: 14px;
}

.filters {
  margin-top: 20px;
  margin-bottom: 20px;

  :deep(.el-date-editor) {
    flex-grow: 0;
    margin-right: 10px;
  }

  .el-select {
    align-items: center;
    width: 320px;
    margin-right: 10px;
  }

  .search-input {
    width: 300px;
    margin-right: 10px;

    :deep(.el-input__inner) {
      line-height: var(--el-input-height);
    }

    .el-select {
      width: 135px;
    }
  }
}

.normal-severity {
  color: #fdf9c6;
  background-color: #f59a23;
}

.high-severity {
  color: #fdf9c6;
  background-color: #d9001b;
}

.low-severity {
  color: #000;
  background-color: #facd91;
}
</style>
